package com.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.util.ResourceUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class QRCodeGenerator {

    public static void generateQRCode(String text, String filePath, int width, int height)
            throws WriterException, IOException {
        Map<EncodeHintType, Object> hintMap = new HashMap<>();
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        hintMap.put(EncodeHintType.MARGIN, 1);
        hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hintMap);

        String path1 = "D:\\jianzhi\\2403\\shipinsuyuan\\food-traceability\\src\\main\\resources\\static\\upload\\";

        String path2 = "D:\\jianzhi\\2403\\shipinsuyuan\\food-traceability\\target\\classes\\static\\upload\\";

        Path path = FileSystems.getDefault().getPath(path1+filePath);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
        Path path3 = FileSystems.getDefault().getPath(path2+filePath);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path3);
    }

    public static void main(String[] args) throws Exception {
        String text = "https://www.example.com";
        String filePath = new Date().getTime()+ "qrcode.png";
        int width = 300;
        int height = 300;
        try {
            generateQRCode(text, filePath, width, height);
            System.out.println("QR Code generated successfully.");
        } catch (WriterException | IOException e) {
            System.out.println("Could not generate QR Code: " + e.getMessage());
        }
    }
}
